package com.chu.cloud.rabbit.listener;

import com.chu.cloud.dto.OrderDelayPay;
import com.chu.cloud.rabbit.dead.DelayConstant;
import com.chu.cloud.rabbit.dead.DelayMessagePayload;
import com.chu.cloud.service.OrderService;
import com.chu.cloud.util.JsonUtils;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/6/1 11:58
 * @Description:
 */
@Slf4j
@Component
@RabbitListener(queues = DelayConstant.FanoutQueue.ORDER_DELAY_PAY)
public class OrderTimeoutPayReceive {

    @Autowired
    private Map<String, OrderService> orderServiceMap;

    @RabbitHandler
    public void process(String payload) {
        log.info("接收到来自队列:{},消息:{}", DelayConstant.FanoutQueue.ORDER_DELAY_PAY, payload);
        log.info("开始处理用户取消订单操作");
        Stopwatch timer = Stopwatch.createStarted();
        try {
            OrderDelayPay orderDelayPay = JsonUtils.json2pojo(payload, OrderDelayPay.class);
            OrderService orderService = orderServiceMap.get(orderDelayPay.getOrderType());
            orderService.cancelOrder(orderDelayPay.getUserId(), orderDelayPay.getOrderNo());
        } catch (Exception e) {
            log.error("未支付关闭订单消费失败", e);
        }
        log.info("处理完订单取消操作, 耗时 {} 秒. ", timer.elapsed(TimeUnit.MILLISECONDS));
    }
}
